import { nanoid10 } from '@/utils';
import { LoadPanel } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import CpasLayout from '~/public/cpas-business/cpas-table/CpasLayout/index';
import BusinessTypeModal from '../../components/search/BusinessTypeModal';
import SearchRenderC from '../../components/search/SearchRenderC';
import { getAccountInfo } from './server';
import {
  buildCol,
  tableColumnsData,
  tableColumnsDataLog,
  tableColumnsStore,
} from './tableColumnsData';
const InventoryAnalysisProductYearAnalysis: React.FC = (props: any) => {
  const pageType = props?.props?.params?.type;
  let typeUrl = 'get.goods.type';
  let dataUrl = 'Analysis.Inventory.SPCRKTJ';

  const cpasNotesRef = useRef<any>(null);
  const businessTypeModal = useRef<any>(null);
  const searchRenderC = useRef<any>();
  const { initialState } = useModel('@@initialState');
  // const yearDateModel: any = useModel('qjModel');
  const ztModel: any = useModel('ztModel');
  const { ztDates } = ztModel;
  const [treeListData, setTreeListData] = useState<any[]>();
  const { dbname, sjnd } = initialState?.curPart as any;
  const [Transaction_Type, setTransaction_Type] = useState<any[]>(['全部']);
  // const [columnsData, setColumnsData] = useState<any[]>([]);
  const [tableData, setTtableData] = useState<any[]>();
  const [Load, setLoad] = useState<any>(false);
  const dataSorce = useRef<any[]>();
  const [selectTreeNode, setSelectTreeNode] = useState<any>(null);
  const [roundid, setRoundid] = useState<any>('roundid');
  const [Years, setYears] = useState<any[]>([]);
  const [isLogNumber, setIslogNumber] = useState<any[]>([]);
  let columnsData =
    '商品规格出入库年度统计' === pageType
      ? [...tableColumnsData, ...tableColumnsStore, ...isLogNumber, ...buildCol(Years)]
      : [...tableColumnsData, ...isLogNumber, ...buildCol(Years)];

  // 查询按钮
  const searchcallback = async () => {
    const q = searchRenderC.current.getFormSearchValues();
    const queryDate = {
      dates: q.dates,
      startYear: q.startYear,
      endYear: q.endYear,
    };
    setRoundid(nanoid10());
    setYears(q.dates);
    let queyType: any = queryDate;
    if (q.TransactionType !== '全部') {
      queyType = { ...queyType, mainType: q.TransactionType };
    }
    if (q.SummeryType !== '按汇总方式') {
      queyType.lotNumber = 1;
      setIslogNumber(tableColumnsDataLog);
    } else {
      setIslogNumber([]);
    }

    await getProductQuery(queyType); // 获取数据接口
  };

  const setSummeryCallback = (a: any, e: any) => {
    if (e === '业务类型设置') {
      businessTypeModal.current.show();
    }
  };
  //商品类型查询,获取数据，首次加载执行，查询按钮执行
  const getProductType = async (a: any, b?: any) => {
    const dd: any = await getAccountInfo(typeUrl, { dbname: dbname }); // 商品类型
    if (dd.data?.length) {
      setTreeListData(
        dd.data.map((a: any) => {
          return {
            ...a,
            typeCode: a.typeCode,
          };
        }),
      );
    }

    await getProductQuery(a);
  };

  // 获取交易类型，刷新，查询先不执行这个
  const getTransactionType = async () => {
    const dd: any = await getAccountInfo('get.Transaction.type', { dbname: dbname });
    if (dd.data?.length) {
      setTransaction_Type(['全部'].concat(dd.data.map((a: any) => a.mainType)));
    }
  };

  // 获取商品数据接口
  const getProductQuery = async (params: {
    startYear: string;
    endYear: string;
    dates: string[];
    mainType?: string;
    lotNumber?: number;
  }) => {
    setLoad(true);

    const dd: any = await getAccountInfo(dataUrl, {
      ...params,
      dbname: dbname,
      dataFieldA: ['Qty', 'Cost'],
      dataFieldB: ['inQty', 'inJE', 'outQty', 'outJE'],
    });
    setLoad(false);

    if (dd.data?.length) {
      // tableData = ;
      const d = dd.data.map((a: any) => {
        return { ...a, xh: a.productCode };
      });
      dataSorce.current = d;
      if (!selectTreeNode) {
        setTtableData(d), console.log(dd.data, 'li w');
      } else {
        setTtableData(d?.filter((a: any) => a.typeID === selectTreeNode));
      }
    }
  };

  const treeClickCallback = async ({ itemData }: any) => {
    setRoundid(nanoid10());
    if (itemData.name === '全部') {
      setTtableData(dataSorce.current);
      setSelectTreeNode(null);
    } else {
      setSelectTreeNode(itemData.id);
      setTtableData(dataSorce.current?.filter((a: any) => a.typeID === itemData.id));
    }
  };

  // 刷新按钮
  const refreshcallback = () => {
    // setRoundid(nanoid10());
    if (ztDates?.length) {
      const q = searchRenderC.current.getFormSearchValues();
      const queryDate = {
        dates: q.dates,
        startYear: q.startYear,
        endYear: q.endYear,
      };
      console.log(1, 'li', queryDate);
      setYears(q.dates);
      let queyType: any = queryDate;
      if (q.TransactionType !== '全部') {
        queyType = { ...queyType, mainType: q.TransactionType };
      }
      if (q.SummeryType !== '按汇总方式') {
        queyType.lotNumber = 1;
        setIslogNumber(tableColumnsDataLog);
      } else {
        setIslogNumber([]);
      }
      getProductType(queyType);
    } else {
      notify('无筛选年度', 'error', 1000);
    }
  };

  const useEffect_Fun = async () => {
    const resZtDates = await ztModel.refresh();
    if (resZtDates?.length) {
      setYears(resZtDates);
      getProductType({
        dates: resZtDates,
        startYear: resZtDates.at(0),
        endYear: resZtDates.at(-1),
      });
    } else {
      notify('无筛选年度', 'error', 1000);
    }
    getTransactionType(); // 业务类型
  };

  useEffect(() => {
    useEffect_Fun();
  }, []);

  function renderSearch() {
    return (
      <SearchRenderC
        yearDate={null}
        ref={searchRenderC}
        pageType={pageType}
        Transaction_Type={Transaction_Type}
        setSummeryCallback={setSummeryCallback}
      />
    );
  }

  return (
    <div
      style={{
        border: '0px solid green',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {treeListData?.length && (
        <CpasLayout
          // key={nanoid10()}
          id="employee"
          ref={cpasNotesRef}
          height={'400px'}
          disabledHomeIcon={true}
          treeListData={treeListData}
          tableColumnsData={columnsData}
          tableData={tableData}
          renderSearch={renderSearch}
          searchClickCallback={searchcallback}
          excelName={pageType}
          isLeftTree={true}
          refreshBtnCallback={refreshcallback}
          treeClickCallback={treeClickCallback}
          isJumpRowDetail={false}
        />
      )}
      <LoadPanel
        // shadingColor="rgba(0,0,0,0.4)"
        position={{ of: '#employee' }}
        // onHiding={hideLoadPanel}
        visible={Load}
        showIndicator={true}
        shading={true}
        showPane={true}
        // hideOnOutsideClick={hideOnOutsideClick}
      />
      <BusinessTypeModal dbname={dbname} ref={businessTypeModal} okCallback={getTransactionType} />
    </div>
  );
};

export default InventoryAnalysisProductYearAnalysis;
